package com.unittec.drainage.provider.manage.common.mybatisTypeHandler;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.postgresql.util.PGobject;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author CopySun
 * @date 2020/9/11 13:34
 */
@MappedJdbcTypes(JdbcType.OTHER)
@MappedTypes({JSONObject.class})
public class ToJsonTypeHandler<T extends JSONObject> extends BaseTypeHandler<T> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        PGobject pGobject = new PGobject();
        pGobject.setType("json");
        pGobject.setValue(parameter.toString());
        ps.setObject(i,pGobject);
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String showJson = (String)rs.getObject(columnName);
        return (T) JSONObject.parse(showJson);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String showJson = (String)rs.getObject(columnIndex);
        return (T) JSONObject.parse(showJson);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String showJson = (String)cs.getObject(columnIndex);
        return (T) JSONObject.parse(showJson);
    }
}
